<template>
  <div class="model-container"  v-loading="loading">
    <el-card>
      <template #header>
        <div class="header">
          <span>模型列表</span>
          <el-button type="primary" @click="handleAdd">添加模型</el-button>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="唯一键" />
        <el-table-column prop="modelName" label="模型名" />
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">
            <el-tag :type="row.type === 'MODEL' ? 'success' : 'info'">
              {{ row.type === 'MODEL' ? '模型' : '向量' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="supplier" label="厂商">
          <template #default="{ row }">
            <el-tag :type="getSupplierTagType(row.supplier)">
              {{ row.supplier }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="responseLength" label="响应长度" />
        <el-table-column prop="temperature" label="温度" />
        <el-table-column prop="top" label="匹配数" />
        <el-table-column prop="dimensions" label="向量维度" />
        <el-table-column prop="ctime" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
       <!-- 分页 -->
       <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

  

    <!-- 添加/编辑模型对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="唯一键" prop="code">
          <el-input v-model="form.code" placeholder="请输入唯一键" />
        </el-form-item>
        <el-form-item label="模型名" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入模型名" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="模型" value="MODEL" />
            <el-option label="向量" value="EMBEDDING" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="厂商" prop="supplier">
          <el-select v-model="form.supplier" placeholder="请选择厂商">
            <el-option label="OLLAMA" value="OLLAMA" />
            <el-option label="千问" value="QWEN" />
            <el-option label="OpenAI" value="OPENAI" />
          </el-select>
        </el-form-item>
        <el-form-item label="响应长度" prop="responseLength">
          <el-input-number v-model="form.responseLength" :min="0" />
        </el-form-item>
        <el-form-item label="温度" prop="temperature">
          <el-input-number v-model="form.temperature" :min="0" :max="1" :step="0.1" />
        </el-form-item>
        <el-form-item label="匹配数" prop="top">
          <el-input-number v-model="form.top" :min="0" />
        </el-form-item>
        <el-form-item label="API Key" prop="apiKey">
          <el-input v-model="form.apiKey" placeholder="请输入API Key" />
        </el-form-item>
        <el-form-item label="Secret Key" prop="secretKey">
          <el-input v-model="form.secretKey" placeholder="请输入Secret Key" />
        </el-form-item>
        <el-form-item label="URL" prop="url">
          <el-input v-model="form.url" placeholder="请输入URL" />
        </el-form-item>
        <el-form-item label="向量维度" prop="dimensions">
          <el-input-number v-model="form.dimensions" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '../../composables/useCommon'

// 表格数据
const tableData = ref([])

// 表格 loading 状态
const loading = ref(false)

// 获取表格数据
const getTableData = async () => {
  try {
    loading.value = true
    const res = await request('ragModel/', 'get', {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      name: searchQuery.value
    })
    tableData.value = res.records
    total.value = res.total
  } catch (err) {
    ElMessage.error('获取模型列表失败')
  } finally {
    loading.value = false
  }
}

// 新增模型
const addModel = async (modelData) => {
  try {
    await request('ragModel/', 'post', modelData)
    ElMessage.success('模型添加成功')
    getTableData()
  } catch (err) {
    ElMessage.error('添加模型失败')
  }
}

// 修改模型
const updateModel = async (modelData) => {
  try {
    await request('ragModel/', 'put', modelData)
    ElMessage.success('模型更新成功')
    getTableData()
  } catch (err) {
    ElMessage.error('更新模型失败')
  }
}

// 删除模型
const deleteModel = async (modelId) => {
  try {
    await request(`ragModel/${modelId}`, 'delete')
    ElMessage.success('模型删除成功')
    getTableData()
  } catch (err) {
    ElMessage.error('删除模型失败')
  }
}

// 搜索
const searchQuery = ref('')
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加模型')
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  code: '',
  modelName: '',
  type: 'MODEL',
  name: '',
  supplier: 'OPENAI',
  responseLength: null,
  temperature: null,
  top: null,
  apiKey: '',
  secretKey: '',
  url: '',
  dimensions: null
})

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入唯一键', trigger: 'blur' }],
  modelName: [{ required: true, message: '请输入模型名', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  supplier: [{ required: true, message: '请选择厂商', trigger: 'change' }]
}

// 处理添加模型
const handleAdd = () => {
  dialogTitle.value = '添加模型'
  Object.keys(form).forEach(key => (form[key] = ''))
  dialogVisible.value = true
}

// 处理编辑模型
const handleEdit = (row) => {
  dialogTitle.value = '编辑模型'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 处理删除模型
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认要删除该模型吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deleteModel(row.id)
    } catch (err) {
      ElMessage.error('删除失败')
    }
  })
}

// 处理表单提交
const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (form.id) {
        updateModel(form)
      } else {
        addModel(form)
      }
      dialogVisible.value = false
    }
  })
}

// 获取厂商标签样式
const getSupplierTagType = (supplier) => {
  switch (supplier) {
    case 'OLLAMA':
      return 'warning'
    case 'QWEN':
      return 'success'
    case 'OPENAI':
      return 'primary'
    default:
      return 'info'
  }
}

// 获取表格数据
getTableData()
</script>

<style scoped>
.model-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

</style>
